﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadPoolExample
{
    class Program
    {
        
        static void Main(string[] args)
        {
            //测试two
            Console.WriteLine("Begin in Main");

            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadDo), 1);
            Thread.Sleep(300);
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadDo), 2);

            Thread.Sleep(300);
            Console.WriteLine("End in Main");

            Thread.Sleep(50000);


            //测试one
            const int FibonacciCalculations = 10;
            // One event is used for each Fibonacci object
            ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
            Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
            Random r = new Random();

            // Configure and launch threads using ThreadPool:
            Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                doneEvents[i] = new ManualResetEvent(false);
                Fibonacci f = new Fibonacci(r.Next(20, 40), doneEvents[i]);
                fibArray[i] = f;
                ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
            }

            // Wait for all threads in pool to calculation...
            WaitHandle.WaitAll(doneEvents);
            Console.WriteLine("All calculations are complete.");

            // Display the results...
            for (int i = 0; i < FibonacciCalculations; i++)
            {
                Fibonacci f = fibArray[i];
                Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
            }

        }

        static void ThreadDo(Object o)
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("[Thread " + (int)o + "] Execute in ThreadDo");
                Thread.Sleep(100);
            }
        }

    }
}
